const { querySql, queryOne , updateSql  ,insertSql , deleteSql } = require('../db')

function getRoleList(query){
  const { roleName , pageNum , pageSize  } = query
  return querySql(`SELECT * FROM role_list WHERE roleName LIKE '%${roleName || ''}%' LIMIT ${(pageNum - 1) * pageSize}, ${pageSize}`)
}

function getTotalCount(query){
  const { roleName } = query
  return queryOne(`SELECT COUNT(*) AS totalCount FROM role_list WHERE roleName LIKE '%${roleName || ''}%'`)
}

function editRole(query){
  query.updateTime = new Date()
  return updateSql( query , 'role_list' , `where id = ${query.id}` )
}

function createRole(query,cardId){
  query.createTime = new Date() 
  query.createId = cardId
  return insertSql( query , 'role_list' )
}

function deleteRole(query){
  return deleteSql('id',query.id,'role_list')
}

function allRole(){
  return querySql(`SELECT * FROM role_list`)
}

function changePermission(query){
  const permissionList = typeof query.permissionList === 'object' ? query.permissionList : JSON.parse(query.permissionList)
  const obj = {
    checkedKeys: typeof permissionList.checkedKeys === 'string' ? permissionList.checkedKeys : JSON.stringify(permissionList.checkedKeys),
    id: query.id,
    halfCheckedKeys : typeof permissionList.halfCheckedKeys === 'string' ? permissionList.halfCheckedKeys : JSON.stringify(permissionList.halfCheckedKeys)
  }
  return updateSql( obj , 'role_list' , `where id = ${query.id}` )
}

function getRoleById(id){
  return queryOne(`SELECT * FROM role_list WHERE id = ${id}`)
}



module.exports = {
  getRoleList,
  getTotalCount,
  editRole,
  createRole,
  deleteRole,
  allRole,
  changePermission,
  getRoleById
}